<?php
namespace App\Models\Goods;
use App\Libs\Base\Constant;
use App\Libs\Helper\CommonHelper;
use App\Models\Store\Store;
class Goods extends \App\Libs\Base\BaseModel
{
    protected $__TABLE__ = 't_paile_goods';
	/**
	*	跳过检测了
	*/
	public function beforeValidation()
	{
	  self::skipValidation(['type','goods_img'] , $this );
	}

    /**
     * 根据传入的商品数组，返回对应的商品信息，其实返回的数组中，键为id
     * @param $goodsId 商品id数组
     * @param $columns 返回列字符串
     * @return mixed  返回以ID为键的商品信息
     */
    public static function getGoodsInfo($goodsId, $columns)
    {

        $goodsInfo = Goods::findAll([
            'conditions' => 'id IN ({GoodsID:array})',
            'columns' => $columns,
//            'columns' => 'id,goods_name,goods_price,sale_price,goods_img',
            'bind' => ['GoodsID' => $goodsId]
        ])->toArray();
        $transFormGoodInfo = CommonHelper::setColToKey($goodsInfo, 'id');
        return $transFormGoodInfo;
    }

    public static function getGoodsInfoforExpGoodsList($goodsId, $columns,$columnKey)
    {

        $goodsInfo = Goods::findAll([
            'conditions' => 'id IN ({GoodsID:array})',
            'columns' => $columns,
//            'columns' => 'id,goods_name,goods_price,sale_price,goods_img',
            'bind' => ['GoodsID' => $goodsId]
        ])->toArray();
        $transFormGoodInfo = CommonHelper::setColToKey($goodsInfo, $columnKey);
        return $transFormGoodInfo;
    }
            

    public static function formatPrice($price){
	    $subNumber = substr($price,strpos($price,'.'),3);
	    $intNumber = (substr($price,0,strpos($price,'.')));
            $intmidArray = str_split((string)$intNumber,1);
            $length = strlen($intNumber);
            $formatArray = [];
            $h=1;
            for($i=0;$i<=$length-1;$i++){
               if($h==3 && $i!==$length-1){
                  $h=1;
                  array_unshift($formatArray,','.array_pop($intmidArray));
               }else{
                  $h++;
                  array_unshift($formatArray,array_pop($intmidArray));
               }
            };
	   return implode('',$formatArray).$subNumber;
    }

    public static function addSaleNumber($gid){
        //增加产品销量这种无关紧要的事，不使用事务;
        //增加产品销量销量：
        $goods = self::find([
            'conditions' => 'id=?1',
            'bind' => [1=>$gid]
        ]);
        $goods->goods_sold = (int)$goods->goods_sold+1;
        $goods->update();

        //增加店铺销量;
        $store = Store::find([
            'conditions' =>'id=?1',
            'bind' =>[1=>$goods->sid]
        ]);
        $store->store_sales = (int)$store->store_sales+1;
        $store->update();
    }
}
